<!-- role component -->
<template>
  <div class="role-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-button
            type="primary"
            @click="insertedRole.insertRoleDialogVisible = true"
            size="small"
          >添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表数据展示 -->
      <div class="role-table">
        <el-table :data="roleList" border stripe style="width: 100%">
          <!-- 权限列表折叠项 -->
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row
                :class="['vcenter', 'divider-bottom', i1 === 0? 'divider-top':'']"
                v-for="(item1, i1) in scope.row.children"
                :key="item1.id"
              >
                <!-- 渲染一级权限 -->
                <el-col :span="5">
                  <el-tag closable @close="revokeAuthById(scope.row, item1.id)">{{ item1.authName }}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 渲染二级和三级权限 -->
                <el-col :span="19">
                  <!-- 通过v-for循环嵌套渲染二级权限 -->
                  <el-row
                    :class="['vcenter', i2 === 0? '':'divider-top']"
                    v-for="(item2, i2) in item1.children"
                    :key="item2.id"
                  >
                    <el-col :span="6">
                      <el-tag
                        type="success"
                        closable
                        @close="revokeAuthById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!-- 渲染三级权限 -->
                    <el-col :span="18">
                      <el-tag
                        type="warning"
                        :class="[i3 === 0? '':'divider-top']"
                        v-for="(item3, i3) in item2.children"
                        :key="item3.id"
                        closable
                        @close="revokeAuthById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column type="index" width="50"></el-table-column>
          <el-table-column prop="roleName" label="角色名称"></el-table-column>
          <el-table-column prop="roleDesc" label="角色描述"></el-table-column>

          <el-table-column label="操作" width="180px">
            <template slot-scope="scope">
              <el-row>
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="updateRoleList(scope.row)"
                ></el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="deleteRoleById(scope.row.id)"
                ></el-button>
                <el-tooltip effect="dark" content="分配权限" placement="top" :enterable="false">
                  <el-button
                    type="warning"
                    size="mini"
                    icon="el-icon-setting"
                    @click="grantAuth(scope.row)"
                  ></el-button>
                </el-tooltip>
              </el-row>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加新角色"
      :visible.sync="insertedRole.insertRoleDialogVisible"
      width="50%"
      @close="resetRoleForm('insertRoleRef')"
    >
      <!-- 内容主体 -->
      <el-form
        :model="insertedRole.insertRoleForm"
        :rules="insertedRole.insertRoleFormRules"
        ref="insertRoleRef"
        label-width="70px"
      >
        <el-form-item label="角色名" prop="roleName">
          <el-input v-model="insertedRole.insertRoleForm.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="insertedRole.insertRoleForm.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="insertedRole.insertRoleDialogVisible = false">取消</el-button>
        <el-button plain @click="resetRoleForm('insertRoleRef')">重置</el-button>
        <el-button type="primary" @click="insertRole('insertRoleRef')">提交</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色对话框 -->
    <el-dialog title="修改角色信息" :visible.sync="updatedRole.updateRoleDialogVisible" width="50%">
      <!-- 内容主体 -->
      <el-form
        :model="updatedRole.updateRoleForm"
        :rules="updatedRole.updateRoleFormRules"
        ref="updateRoleRef"
        label-width="70px"
      >
        <el-form-item label="角色名" prop="roleName">
          <el-input v-model="updatedRole.updateRoleForm.roleName" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="updatedRole.updateRoleForm.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="updatedRole.updateRoleDialogVisible = false">取消</el-button>
        <el-button plain @click="resetRoleForm('updateRoleRef')">重置</el-button>
        <el-button type="primary" @click="updateRole('updateRoleRef')">提交</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="grantAuthDialogVisible"
      width="50%"
      @close="grantAuthDialogClosed"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="authList"
        show-checkbox
        node-key="id"
        ref="grantAuthRef"
        :default-expand-all="true"
        :default-checked-keys="keys"
        :props="defaultProps"
        @check-change="handleCheckChange"
      ></el-tree>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="grantAuthDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateAuthOfRole">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleList: [],
      // 添加用户对象
      insertedRole: {
        insertRoleDialogVisible: false,
        insertRoleForm: {
          roleName: '',
          roleDesc: ''
        },
        // 添加表单项校验规则
        insertRoleFormRules: {
          roleName: [
            { required: true, message: '角色名称不能为空', triggle: 'blur' }
          ]
        }
      },
      // 修改用户对象
      updatedRole: {
        updateRoleDialogVisible: false,
        updateRoleForm: {},
        insertRoleFormRules: {}
      },
      grantAuthDialogVisible: false, // 控制分配权限对话框显示和隐藏
      authList: [], // 所有权限列表
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      currentRoleId: 0,
      keys: [] // 默认选中权限ID数组
    }
  },

  created() {
    this.getRoleList()
  },

  methods: {
    // 获取角色列表
    getRoleList() {
      this.axios.get('roles').then(resp => {
        if (resp.meta.status !== 200) {
          return this.$message.error('获取角色列表失败')
        }
        this.$message.success({ message: '获取角色列表成功', duration: 500 })
        this.roleList = resp.data
      })
    },
    // 修改用户角色信息
    updateRoleList(role) {
      this.updatedRole.updateRoleDialogVisible = true
      this.updatedRole.updateRoleForm = role
    },
    // 修改用户提交
    updateRole(roleName) {
      this.axios
        .put(
          `roles/${this.updatedRole.updateRoleForm.id}`,
          this.updatedRole.updateRoleForm
        )
        .then(resp => {
          if (resp.meta.status !== 200) {
            return this.$message.error('修改角色信息失败，请重新修改')
          }
          // 修改成功
          this.$message.success({
            message: '修改角色信息成功',
            duration: 600
          })
        })
      this.updatedRole.updateRoleDialogVisible = false
    },
    // 删除用户角色
    deleteRoleById(roleId) {
      this.$confirm(
        '此操作将会永久删除该用户，确定要删除吗',
        'Warning',
        {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          // 确认删除，执行删除操作
          this.axios.delete(`roles/${roleId}`).then(resp => {
            if (resp.meta.status !== 200) {
              return this.$message.error('删除角色失败')
            }
            // 成功删除
            this.getRoleList()
            this.$message.success({
              message: '删除角色成功',
              duration: 600
            })
          })
        })
        .catch(() => {
          // 取消删除
          this.$message.info('已取消删除')
        })
    },
    // 重置角色表单
    resetRoleForm(roleName) {
      this.$refs[roleName].resetFields()
    },
    // 添加用户提交
    insertRole(roleName) {
      // 校验
      this.$refs[roleName].validate(valid => {
        if (!valid) {
          return this.$message.error('校验失败，请重新添加')
        }
        this.axios
          .post('roles', this.insertedRole.insertRoleForm)
          .then(resp => {
            if (resp.meta.status !== 201) {
              return this.$message.error('添加失败，请重新添加')
            }
            // 添加成功,重新请求角色列表
            this.getRoleList()
            this.$message.success({
              message: '添加角色权限成功',
              duration: 600
            })
          })
      })
      this.insertedRole.insertRoleDialogVisible = false
    },

    // 根据指定角色id撤销指定id权限
    revokeAuthById(role, authId) {
      // 删除确认
      this.$confirm(
        '此操作将会永久删除该用户的这个权限，确定要删除吗',
        'Warning',
        {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          // 确认删除，执行删除操作
          this.axios.delete(`roles/${role.id}/rights/${authId}`).then(resp => {
            if (resp.meta.status !== 200) {
              return this.$message.error('删除权限失败')
            }
            // 成功删除
            role.children = resp.data
            this.$message.success({
              message: '删除角色权限成功',
              duration: 600
            })
          })
        })
        .catch(() => {
          // 取消删除
          this.$message.info('已取消删除')
        })
    },
    // 给指定id的角色分配权限
    grantAuth(node) {
      // 获取权限
      this.axios.get('rights/tree').then(resp => {
        if (resp.meta.status !== 200) {
          return this.$message.error('获取权限列表失败！')
        }
        this.authList = resp.data
        this.$message.success({
          message: '获取角色权限成功',
          duration: 600
        })
        this.getIdOfAuths(node, this.keys)
        this.currentRoleId = node.id
        this.grantAuthDialogVisible = true
      })
    },
    // 获取角色三级权限权限的ID数组
    getIdOfAuths(node, array) {
      // 递归获取
      if (!node.children) {
        return array.push(node.id)
      }
      node.children.forEach(item => {
        this.getIdOfAuths(item, array)
      })
    },
    // 处理分配权限对话框复选框的选中变化
    handleCheckChange(data, checked, indeterminate) {
      // console.log(data, checked, indeterminate)
    },
    // 分配权限对话框关闭触发
    grantAuthDialogClosed() {
      this.keys = []
      this.currentRoleId = 0
    },
    // 提交指定ID角色权限修改
    updateAuthOfRole() {
      // 获取所有选中权限ID和半选中权限ID
      const keys = [
        ...this.$refs.grantAuthRef.getCheckedKeys(),
        ...this.$refs.grantAuthRef.getHalfCheckedKeys()
      ]
      // 合并权限ID数组，作为post方法体
      this.axios
        .post(`roles/${this.currentRoleId}/rights`, { rids: keys.join(',') })
        .then(resp => {
          if (resp.meta.status !== 200) {
            return this.$message.error('修改角色权限失败！')
          }
          this.$message.success({
            message: '修改角色权限成功',
            duration: 600
          })
          // 修改成功，重新获取角色信心
          this.getRoleList()
          this.grantAuthDialogVisible = false
        })
    }
  },

  components: {}
}
</script>

<style lang='scss' scoped>
.role-container {
  .role-table {
    margin: 10px 0;

    .el-tag {
      margin: 7px;
    }
  }
}
.divider-top {
  border-top: 1px solid #eee;
}
.divider-bottom {
  border-bottom: 1px solid #eee;
}
//垂直方向居中
.vcenter {
  display: flex;
  align-items: center;
}
</style>
